package com.example.springtransation.controller;

import com.example.springtransation.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-30
 * Time: 19:35
 */
@RestController
@RequestMapping("/trans")
@Slf4j
public class TransactionalController {
    @Autowired
    private UserService userService;
    /*
    * 程序正常执行，数据插入成功*/
    @Transactional//事务化
    @RequestMapping("/registry")
    public String registry(String name , String password){
        userService.registryUser(name,password);
        log.info("用户数据插入成功");
        return "注册成功";
    }

    /*
    * 强制让程序报错，虽然打印了，用户数据插入成功，但是数据库并没有看到新增的数据，事务进行了回滚，*/
    @Transactional//事务化
    @RequestMapping("/registry2")
    public String registry2(String name , String password){
        userService.registryUser(name,password);
        log.info("用户数据插入成功");
        //强制让程序报错
        int a = 10/0;
        return "注册成功";
    }
    /*
    * 有异常被捕获了，只是进行了堆栈的追踪，事务不会进行回滚*/
    @Transactional//事务化
    @RequestMapping("/registry3")
    public String registry3(String name , String password){
        userService.registryUser(name,password);
        log.info("用户数据插入成功");
        try {
            //强制让程序报错
            int a = 10/0;
        }catch(Exception e){
            e.printStackTrace();
        }
        return "注册成功";
    }

    /*
    * 有异常了，把异常在抛出去，事务会回滚*/
    @Transactional//事务化
    @RequestMapping("/registry4")
    public String registry4(String name , String password){
        userService.registryUser(name,password);
        log.info("用户数据插入成功");
        try {
            //强制让程序报错
            int a = 10/0;
        }catch(Exception e){
            throw e;
        }
        return "注册成功";
    }

    /*
    * 捕获到异常，手动进行事务回滚*/
    @Transactional//事务化
    @RequestMapping("/registry5")
    public String registry5(String name , String password){
        userService.registryUser(name,password);
        log.info("用户数据插入成功");
        try {
            //强制让程序报错
            int a = 10/0;
        }catch(Exception e){
            // ⼿动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return "注册成功";
    }
}
